package com.zunipe.trainticketsystem.ui.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.zunipe.trainticketsystem.databinding.FragmentTrainListBinding;
import com.zunipe.trainticketsystem.ui.adapter.TrainListAdapter;

public class TrainListFragment extends Fragment {
    FragmentTrainListBinding binding;
    private BroadcastReceiver broadcastReceiver;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = FragmentTrainListBinding.inflate(inflater, container, false);

        RecyclerView recyclerView = binding.rvTrainList;
        recyclerView.setLayoutManager(new LinearLayoutManager(requireContext()));
        TrainListAdapter adapter = new TrainListAdapter();
        recyclerView.setAdapter(adapter);

        broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                adapter.updateUI();
            }
        };
        requireActivity().registerReceiver(broadcastReceiver, new IntentFilter("com.zunipe.trainticketsystem.update.home.list"), Context.RECEIVER_NOT_EXPORTED);

        return binding.getRoot();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (broadcastReceiver != null)
            requireActivity().unregisterReceiver(broadcastReceiver);
    }
}
